package com.example.demo.web;

import com.example.demo.util.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class FileSystemService {

    @Resource
    private MinioUtil minioUtil;

    public void fileUploadByFilePath(String objectName, String filePath) {
        minioUtil.fileUploadByFilePath(objectName, filePath);
    }

    public void fileUploadByImageData(String objectName, String imageData) {
        minioUtil.fileUploadByImageData(objectName, imageData);
    }

    public void fileDownload(String objectName, String targetFilePath) {
        minioUtil.fileDownload(objectName, targetFilePath);
    }

    public void fileDelete(String objectName) {
        minioUtil.fileDelete(objectName);
    }

    public ResponseEntity<byte[]> getPicture(String objectName) {

        InputStream inputStream = minioUtil.filePreview(objectName);
        byte[] imageBytes = {};
        try {
            imageBytes = inputStreamToByteArray(inputStream);
            inputStream.close();
        } catch (IOException e) {
            log.error("getPicture [{}] Failed [{}]", objectName, e.getMessage());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }

    public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 用于缓存数据的字节数组
        byte[] buffer = new byte[1024];
        int bytesRead;
        // 从输入流中读取数据，然后写入到ByteArrayOutputStream中
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        return byteArrayOutputStream.toByteArray();
    }

    public void bucketRemove(String bucketName) {
        minioUtil.bucketRemove(bucketName);
    }
}
